//
//  DeinitializeVC.swift
//  swiftDemo
//
//  Created by mac on 2017/3/23.
//  Copyright © 2017年 毕小强. All rights reserved.
//
//  反初始化，析构

import UIKit

class DeinitializeVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        var player1:Player? = Player(coins: 100)
        player1!.win(coins: 200)
        let player2:Player? = Player(coins: 100)
        player2!.win(coins: 500)
        print("银行当前存款:\(Bank.coinTotal)")
        player1 = nil
        print("玩家1离开后银行存款:\(Bank.coinTotal)")
        // Do any additional setup after loading the view.
    }
    
    /*
     *      只有类中才有析构器,类似于OC中的delloc
     **/
    class Bank {
        static var coinTotal = 2000
        static func distribute(coins:Int)->Int{
            var realCoins :Int
            realCoins = min(coinTotal, coins)
            coinTotal -= realCoins
            return realCoins
        }
        
        static func recive(coins:Int){
            coinTotal += coins
        }
    }
    
    class Player {
        var currentCoins:Int
        init(coins:Int) {
            currentCoins = Bank.distribute(coins: coins)
        }
        
        func win(coins:Int)  {
            currentCoins += Bank.distribute(coins: coins)
        }
        
        deinit {
            Bank.recive(coins: currentCoins)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
